package com.xuecheng.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.order.utils.PayUtils;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 订单支付信息 服务实现类
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private PayUtils payUtils;
    //创建支付信息，获取微信支付的二维码
    @Override
    public ResponseResult<String> createPay(String orderNo) {
        //1.查询订单，判断订单状态是否为已创建，未支付状态
        LambdaQueryWrapper<Orders> wq = new LambdaQueryWrapper<>();
        wq.eq(Orders::getOrderNo, orderNo);
        Orders one = ordersService.getOne(wq);
        if (!one.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //2.查询支付信息，判断是否存在
        LambdaQueryWrapper<Payment> wq1 = new LambdaQueryWrapper<>();
        wq1.eq(Payment::getOrderNo,orderNo);
        Payment payment = getOne(wq1);
        //3.不存在时，构造支付数据，存入数据库
        if (payment == null) {
            payment = new Payment();
            payment.setUserId(AuthInfoHolder.getUserId());
            payment.setOrderNo(orderNo);
            payment.setCompanyId(one.getCompanyId());
            payment.setTotalAmount(one.getPrice());
            payment.setCreateDate(new Date());
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);//支付方式
            payment.setStatus(OrdersConstants.NOT_PAID.toString());
            boolean save = save(payment);
            if (!save) {
                throw new BusinessException(ErrorCode.ERROR);
            }
        }
        //4.调用微信工具类生成二维码
        String url = payUtils.createOrder(orderNo, one.getPrice(), one.getCoursePubName());
        return ResponseResult.okResult(url);
    }
}
